import { ref, reactive, onMounted, computed } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import {
  getUserList,
  getUserDetail,
  createUser,
  updateUser,
  deleteUser,
  batchDeleteUsers,
  updateUserStatus,
  resetUserPassword
} from '@/api/user'
import request from '@/utils/request'

/**
 * 用户管理业务逻辑Hook
 * @returns {Object} 用户管理相关的状态和方法
 */
export function useUserList() {
  // 加载状态
  const loading = ref(false)
  const tableLoading = ref(false)
  const submitLoading = ref(false)

  // 用户列表数据
  const userList = ref([])
  const total = ref(0)
  const currentUser = ref(null)

  // 分页参数
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })

  // 查询参数
  const searchParams = reactive({
    keyword: '',
    role: '',
    status: '',
    dateRange: []
  })

  // 选中的用户
  const selectedRowKeys = ref([])
  const selectedUsers = ref([])

  // 弹窗状态
  const dialogVisible = ref(false)
  const detailVisible = ref(false)
  const roleAssignVisible = ref(false)
  
  // 表单模式
  const formMode = ref('create') // 'create' | 'edit'

  // 计算属性
  const hasSelectedUsers = computed(() => selectedRowKeys.value.length > 0)
  const selectedCount = computed(() => selectedRowKeys.value.length)

  /**
   * 获取用户列表
   */
  const fetchUserList = async (params = {}) => {
    try {
      tableLoading.value = true
      
      const queryParams = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
        ...params
      }

      const response = await getUserList(queryParams)
      
      if (response.code === 200) {
        userList.value = response.data.list || []
        total.value = response.data.total || 0
        pagination.total = response.data.total || 0
      } else {
        MessagePlugin.error(response.message || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      MessagePlugin.error('获取用户列表失败')
    } finally {
      tableLoading.value = false
    }
  }

  /**
   * 获取用户详情
   */
  const fetchUserDetail = async (userId) => {
    try {
      loading.value = true
      const response = await getUserDetail(userId)
      
      if (response.code === 200) {
        currentUser.value = response.data
        return response.data
      } else {
        MessagePlugin.error(response.message || '获取用户详情失败')
        return null
      }
    } catch (error) {
      console.error('获取用户详情失败:', error)
      MessagePlugin.error('获取用户详情失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建用户
   */
  const handleCreateUser = async (userData) => {
    try {
      submitLoading.value = true
      const response = await createUser(userData)
      
      if (response.code === 200) {
        MessagePlugin.success('创建用户成功')
        dialogVisible.value = false
        await fetchUserList()
        return true
      } else {
        MessagePlugin.error(response.message || '创建用户失败')
        return false
      }
    } catch (error) {
      console.error('创建用户失败:', error)
      MessagePlugin.error('创建用户失败')
      return false
    } finally {
      submitLoading.value = false
    }
  }

  /**
   * 更新用户
   */
  const handleUpdateUser = async (userId, userData) => {
    try {
      submitLoading.value = true
      const response = await updateUser(userId, userData)
      
      if (response.code === 200) {
        MessagePlugin.success('更新用户成功')
        dialogVisible.value = false
        await fetchUserList()
        return true
      } else {
        MessagePlugin.error(response.message || '更新用户失败')
        return false
      }
    } catch (error) {
      console.error('更新用户失败:', error)
      MessagePlugin.error('更新用户失败')
      return false
    } finally {
      submitLoading.value = false
    }
  }

  /**
   * 删除用户
   */
  const handleDeleteUser = async (userId, username) => {
    const confirmRes = await DialogPlugin.confirm({
      header: '删除确认',
      body: `确定要删除用户"${username}"吗？此操作不可撤销。`,
      theme: 'danger'
    })

    if (confirmRes) {
      try {
        loading.value = true
        const response = await deleteUser(userId)
        
        if (response.code === 200) {
          MessagePlugin.success('删除用户成功')
          await fetchUserList()
        } else {
          MessagePlugin.error(response.message || '删除用户失败')
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        MessagePlugin.error('删除用户失败')
      } finally {
        loading.value = false
      }
    }
  }

  /**
   * 批量删除用户
   */
  const handleBatchDelete = async () => {
    if (selectedRowKeys.value.length === 0) {
      MessagePlugin.warning('请选择要删除的用户')
      return
    }

    const confirmRes = await DialogPlugin.confirm({
      header: '批量删除确认',
      body: `确定要删除选中的${selectedRowKeys.value.length}个用户吗？此操作不可撤销。`,
      theme: 'danger'
    })

    if (confirmRes) {
      try {
        loading.value = true
        const response = await batchDeleteUsers({ userIds: selectedRowKeys.value })
        
        if (response.code === 200) {
          MessagePlugin.success(`成功删除${selectedRowKeys.value.length}个用户`)
          selectedRowKeys.value = []
          selectedUsers.value = []
          await fetchUserList()
        } else {
          MessagePlugin.error(response.message || '批量删除失败')
        }
      } catch (error) {
        console.error('批量删除失败:', error)
        MessagePlugin.error('批量删除失败')
      } finally {
        loading.value = false
      }
    }
  }

  /**
   * 更新用户状态
   */
  const handleUpdateStatus = async (userId, status, username) => {
    const statusText = status === 'active' ? '启用' : '禁用'
    
    const confirmRes = await DialogPlugin.confirm({
      header: '状态变更确认',
      body: `确定要${statusText}用户"${username}"吗？`,
      theme: status === 'active' ? 'primary' : 'warning'
    })

    if (confirmRes) {
      try {
        loading.value = true
        const response = await updateUserStatus(userId, { status })
        
        if (response.code === 200) {
          MessagePlugin.success(`${statusText}用户成功`)
          await fetchUserList()
        } else {
          MessagePlugin.error(response.message || `${statusText}用户失败`)
        }
      } catch (error) {
        console.error(`${statusText}用户失败:`, error)
        MessagePlugin.error(`${statusText}用户失败`)
      } finally {
        loading.value = false
      }
    }
  }

  /**
   * 重置用户密码
   */
  const handleResetPassword = async (userId, username) => {
    const confirmRes = await DialogPlugin.confirm({
      header: '重置密码确认',
      body: `确定要重置用户"${username}"的密码吗？重置后的新密码将发送给用户。`,
      theme: 'warning'
    })

    if (confirmRes) {
      try {
        loading.value = true
        const response = await resetUserPassword(userId)
        
        if (response.code === 200) {
          MessagePlugin.success('重置密码成功，新密码已发送给用户')
        } else {
          MessagePlugin.error(response.message || '重置密码失败')
        }
      } catch (error) {
        console.error('重置密码失败:', error)
        MessagePlugin.error('重置密码失败')
      } finally {
        loading.value = false
      }
    }
  }

  /**
   * 搜索用户
   */
  const handleSearch = () => {
    pagination.current = 1
    fetchUserList()
  }

  /**
   * 重置搜索
   */
  const handleResetSearch = () => {
    Object.assign(searchParams, {
      keyword: '',
      role: '',
      status: '',
      dateRange: []
    })
    pagination.current = 1
    fetchUserList()
  }

  /**
   * 分页变化
   */
  const handlePageChange = (pageInfo) => {
    pagination.current = pageInfo.current
    pagination.pageSize = pageInfo.pageSize
    fetchUserList()
  }

  /**
   * 选择变化
   */
  const handleSelectionChange = (value, { selectedRowData }) => {
    selectedRowKeys.value = value
    selectedUsers.value = selectedRowData
  }

  /**
   * 打开新建用户弹窗
   */
  const openCreateDialog = () => {
    formMode.value = 'create'
    currentUser.value = null
    dialogVisible.value = true
  }

  /**
   * 打开编辑用户弹窗
   */
  const openEditDialog = async (userId) => {
    const user = await fetchUserDetail(userId)
    if (user) {
      formMode.value = 'edit'
      dialogVisible.value = true
    }
  }

  /**
   * 打开用户详情
   */
  const openUserDetail = async (userId) => {
    const user = await fetchUserDetail(userId)
    if (user) {
      detailVisible.value = true
    }
  }

  /**
   * 打开角色分配弹窗
   */
  const openRoleAssignDialog = async (userId) => {
    if (userId) {
      // 单用户角色分配
      const user = await fetchUserDetail(userId)
      if (user) {
        roleAssignVisible.value = true
      }
    } else {
      // 批量角色分配
      if (selectedRowKeys.value.length > 0) {
        roleAssignVisible.value = true
      } else {
        MessagePlugin.warning('请先选择要分配角色的用户')
      }
    }
  }

  /**
   * 处理角色分配
   */
  const handleRoleAssign = async (assignData) => {
    try {
      submitLoading.value = true
      const response = await request({
        url: '/api/v1/users/assign-roles',
        method: 'post',
        data: assignData
      })
      
      if (response.code === 200) {
        MessagePlugin.success(response.message || '角色分配成功')
        roleAssignVisible.value = false
        selectedRowKeys.value = []
        selectedUsers.value = []
        await fetchUserList()
        return true
      } else {
        MessagePlugin.error(response.message || '角色分配失败')
        return false
      }
    } catch (error) {
      console.error('角色分配失败:', error)
      MessagePlugin.error('角色分配失败')
      return false
    } finally {
      submitLoading.value = false
    }
  }

  /**
   * 关闭弹窗
   */
  const closeDialog = () => {
    dialogVisible.value = false
    detailVisible.value = false
    roleAssignVisible.value = false
    currentUser.value = null
  }

  // 初始化
  onMounted(() => {
    fetchUserList()
  })

  return {
    // 状态
    loading,
    tableLoading,
    submitLoading,
    userList,
    total,
    currentUser,
    pagination,
    searchParams,
    selectedRowKeys,
    selectedUsers,
    dialogVisible,
    detailVisible,
    roleAssignVisible,
    formMode,
    
    // 计算属性
    hasSelectedUsers,
    selectedCount,
    
    // 方法
    fetchUserList,
    fetchUserDetail,
    handleCreateUser,
    handleUpdateUser,
    handleDeleteUser,
    handleBatchDelete,
    handleUpdateStatus,
    handleResetPassword,
    handleSearch,
    handleResetSearch,
    handlePageChange,
    handleSelectionChange,
    openCreateDialog,
    openEditDialog,
    openUserDetail,
    openRoleAssignDialog,
    handleRoleAssign,
    closeDialog
  }
} 